package goodenglish.infrastructure.repository.db;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理器
 * 
 * @author qiujy
 * @version 0.9Beta
 */
public class TransactionManager {
	private Connection conn;

	protected TransactionManager(Connection conn) {
		this.conn = conn;
	}

	/**
	 * 获取事务管理器
	 * 
	 * @return 事务管理实例
	 */
	public static synchronized TransactionManager getTranManager() {
		return new TransactionManager(DBUtil.getTxConnection());
	}

	/** 开启事务 */
	public void beginTransaction() throws DaoException {
		try {
			conn.setAutoCommit(false); // 把事务提交方式改为手工提交
		} catch (SQLException e) {
			throw new DaoException("开户事务时出现异常", e);
		}
	}

	/** 提交事务并关闭连接 */
	public void commit() throws DaoException {
		try {
			conn.commit(); // 提交事务
			DBUtil.closeTxConnection(conn);
		} catch (SQLException e) {
			throw new DaoException("提交事务时出现异常", e);
		}
	}

	/** 回滚并关闭连接 */
	public void rollback() {
		try {
			conn.rollback();
		} catch (SQLException e) {
			throw new RuntimeException("回滚事务时出现异常", e);
		} finally {
			DBUtil.closeTxConnection(conn);
		}
	}
}
